package top.starmc.starpet.internal

import org.bukkit.Material
import taboolib.common.util.replaceWithOrder
import taboolib.library.configuration.ConfigurationSection
import taboolib.module.configuration.util.getStringColored
import taboolib.module.configuration.util.getStringListColored
import taboolib.module.nms.ItemTagData
import taboolib.module.nms.getItemTag
import taboolib.platform.util.buildItem
import top.starmc.starpet.util.calculate
import top.starmc.starpet.util.updatePetData
import java.util.*

class PetData(config: ConfigurationSection) {
    val maxLevel = config.getInt("max-level")

    val itemLore = config.getStringListColored("item.lore")

    val levelStats = TreeMap<Int, MutableList<String>>().apply {
        config.getConfigurationSection("level-stats")?.let {
            it.getKeys(false).forEach { key ->
                getOrPut(key.toInt()) {
                    mutableListOf()
                } += it.getStringList(key)
            }
        }
    }

    private val levelMap = LinkedHashMap<Int, Int>().apply {
        val formula = config.getString("level-formula")!!
        for (i in 1 until maxLevel) {
            this[i] = formula.replaceWithOrder(i).calculate().toInt()
        }
    }

    val internalItem = buildItem(Material.valueOf(config.getString("item.type")!!)) {
        name = config.getStringColored("item.display")
    }.apply {
        val tag = getItemTag()
        tag["宠物"] = ItemTagData(config.name)
        tag.saveTo(this)
    }.updatePetData(this, 0, 1)

    val levelNameMap = TreeMap<Int, String>().apply {
        config.getConfigurationSection("level-name")?.let {
            it.getKeys(false).forEach { key ->
                this[key.toInt()] = it.getStringColored(key)!!
            }
        }
    }

    val skillMap = HashMap<String, MutableList<SkillData>>().apply {
        config.getConfigurationSection("skill")?.let {
            it.getKeys(false).forEach { key ->
                val skill = SkillData(it.getConfigurationSection(key)!!)
                getOrPut(skill.type) {
                    mutableListOf()
                } += skill
            }
        }
    }

    fun getMaxExp(level: Int): Int {
        return levelMap.getOrDefault(level, -1)
    }
}